var express = require('express');
var router = express.Router();
const BizResult = require("../config/BizResult");
// mongodb
const AccountModel = require('../models/AccountModel');
const CategoryModel = require('../models/CategoryModel');
const commona = require('../utils/commonality');



router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 解析请求体的中间件
const bodyParser = require('body-parser');
// 解析 querystring 格式请求体的中间件 【url编码】
let urlParser = bodyParser.urlencoded({ extended: false });
// 解析 JSON 格式请求体的中间件
let jsonParser = bodyParser.json();


/* 记账本列表 */
router.get('/account/list', function (req, res, next) {
  let { recordingTime, pageSize, pageNum, keyword,userId } = req.query;
  // 获取时间当月的第一天和最后一天
  let monthWeek = commona.getMonthWeek(recordingTime);
  AccountModel.find({
    $and: [{
      recordingTime: { $lt: monthWeek[1] }
    }, { recordingTime: { $gt: monthWeek[0] } }],
    $or: [{ remark: new RegExp(keyword) }, { catalogueName: new RegExp(keyword) }],
    userId,
  }).sort({ creationTime: -1 }).then((data, err) => {
    if (err) {
      res.send(BizResult.fail(err))
      return false;
    }
    let totalIncome = 0;//总收入
    let totalDisburse = 0;//总支出
    data.forEach(e => {
      if (e.type == 2) totalIncome += e.money;
      if (e.type == 1) totalDisburse += e.money;
    })

    res.send(BizResult.success({
      list: data,
      totalIncome,
      totalDisburse
    }))
  })
});
/* 记账本详情 */
router.get('/account/details', function (req, res, next) {
  let { id } = req.query;
  AccountModel.findOne({
    _id: id
  }).then((data, err) => {
    if (err) {
      res.send(BizResult.fail(err))
      return false;
    }
    res.send(BizResult.success(data))
  })
});


// 添加账单
router.post('/account/create', urlParser, (req, res) => {
  const { catalogueType, money } = req.body;
  let objData = req.body;
  if (!catalogueType || catalogueType == null) {
    return res.send(BizResult.fail('录入的类型不能为空'))
  }
  if (!money || money == null || money <= 0) {
    return res.send(BizResult.fail('录入的金额必须大于0'))
  }

  CategoryModel.findOne({ type: catalogueType }).then((dataT, err) => {
    // 失败
    if (err) return res.send(BizResult.fail('类目选择错误'));
    let { icon, name } = dataT;
    // 获取请求体
    AccountModel.create({ ...objData, catalogueIcon: icon, catalogueName: name }).then((data, err) => {
      // 失败
      if (err) return res.send(BizResult.fail(err))
      res.send(BizResult.success('添加成功'));
    })
  })

});

// 编辑账单
router.post('/account/update', urlParser, (req, res) => {
  const { catalogueType, money, _id, remark, type } = req.body;
  let objData = req.body;
  if (!catalogueType || catalogueType == null) {
    return res.send(BizResult.fail('录入的类型不能为空'))
  }
  if (!money || money == null || money <= 0) {
    return res.send(BizResult.fail('录入的金额必须大于0'))
  }

  CategoryModel.findOne({ type: catalogueType }).then((dataT, err) => {
    // 失败
    if (err) return res.send(BizResult.fail('类目选择错误'));
    let { icon, name } = dataT;
    console.log(objData)
    // 获取请求体
    AccountModel.updateOne({ _id }, {
      type,
      catalogueType,
      money,
      remark,
      catalogueIcon: icon,
      catalogueName: name,
      creationTime: new Date()
    }).then((data, err) => {
      // 失败
      if (err) return res.send(BizResult.fail(err))
      res.send(BizResult.success('修改成功'));
    })
  })

});

// 删除对应数据
router.post('/account/delete', urlParser, (req, res) => {
  // 获取请求体
  const { id } = req.body;
  AccountModel.deleteMany({ _id: id }).then((data, err) => {
    // 失败
    if (err) return res.send(BizResult.fail(err))
    res.send(BizResult.success('删除成功'))
  })
});


module.exports = router;
